<?php
/**
 * aheadWorks Co.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the EULA
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://ecommerce.aheadworks.com/AW-LICENSE-COMMUNITY.txt
 * 
 * =================================================================
 *                 MAGENTO EDITION USAGE NOTICE
 * =================================================================
 * This package designed for Magento COMMUNITY edition
 * aheadWorks does not guarantee correct work of this extension
 * on any other Magento edition except Magento COMMUNITY edition.
 * aheadWorks does not provide extension support in case of
 * incorrect edition usage.
 * =================================================================
 *
 * @category   AW
 * @package    AW_Vidtest
 * @copyright  Copyright (c) 2010-2011 aheadWorks Co. (http://www.aheadworks.com)
 * @license    http://ecommerce.aheadworks.com/AW-LICENSE-COMMUNITY.txt
 */
/**
 * Youtube Upload Controller
 */
class AW_Vidtest_YoutubeController extends Mage_Core_Controller_Front_Action
{
    /** 
     * Getting new video status config path
     */
    const GET_STATUS_PATH = 'vidtest/general/new_video_status';

    /**
     * Retrives Youtube Api Model
     * @return AW_Vidtest_Model_Api_Youtube
     */
    protected function _getApiModel()
    {
        return Mage::getSingleton('vidtest/connector')->getApiModel('youtube');
    }

    /**
     * Retrives parsed video id from
     * [http://www.youtube.com/watch?v=<id>]
     * @param string $url
     * @return string
     */
    protected function _getParsedVideoId($url)
    {
        if (html_entity_decode($url)){
            $arr = explode("?", $url);
            if (isset($arr[1])){
                $arr = explode("&", $arr[1]);
                $newArr = array();
                foreach($arr as $a){
                    try {
                        list($param, $value) = explode("=",$a);
                        $newArr[$param] = $value;
                    } catch(Exception $e) {
                        Mage::helper('vidtest')->addCustomerError('Invalid youtube url');
                        return null;
                    }
                }
                if (isset($newArr['v'])){
                    return $newArr['v'];
                } else {
                    Mage::helper('vidtest')->addCustomerError('Invalid youtube url');
                }
            }
        }        
        return null;
    }

    /**
     * Move tmp uploaded file
     * @param string $filename File name
     * @return boolean
     */
    protected function _removeTempFile($filename)
    {
        if (file_exists($filename)){
            try {
                unlink($filename);
            } catch(Exception $e) {
                return false;
            }
        }
        return true;
    }

    /**
     * Get customer video
     */
    public function postAction()
    {
        $data = new Varien_Object($this->getRequest()->getPost());
        $file = new Varien_Object(isset($_FILES['video_file']) ? $_FILES['video_file'] : array());

        if (!Mage::helper('vidtest')->canUpload()){
            Mage::helper('vidtest')->addCustomerError(Mage::helper('vidtest')->__('You can not upload video'));
            $this->_removeTempFile($file->getTmpName());
            $this->_redirectReferer();
            return;
        }

        if ($file->getError() && $data->getVideoType() == 'file'){
            Mage::helper('vidtest')->addCustomerError('Video upload error');
            return;
        }

        $helper = Mage::helper('vidtest');

        if ($data->getExtData() == $helper->getValue('youtube_secret_key')){
            # Clean key for next post
//            $helper->setValue('youtube_secret_key', null);

            $video = Mage::getModel('vidtest/video');

            # Set up basical info
            $video->setTitle(htmlspecialchars($data->getTitle()));
            $video->setComment($data->getComment());
            $video->setProductId($data->getProductId());
            $video->setAuthorName(htmlspecialchars($data->getAuthorName()));
            $video->setAuthorEmail($data->getAuthorEmail());
            $video->setApiCode('youtube');
            $video->setStore(Mage::app()->getStore()->getId());
            $video->setState(AW_Vidtest_Model_Video::VIDEO_STATE_PROCESSING);

            # Set up access info
            if (Mage::getStoreConfig(self::GET_STATUS_PATH)){
                $video->setStatus(AW_Vidtest_Model_Video::VIDEO_STATUS_ENABLED);
            } else {
                $video->setStatus(AW_Vidtest_Model_Video::VIDEO_STATUS_PENDING);
            }            
           
            try {
                if ($data->getVideoType() == 'link'){                                                                             
                    $entry = $this->_getApiModel()->getVideoData($this->_getParsedVideoId($data->getVideoLink()));
                    if ($entry->getError()){
                        $entry = $this->_getApiModel($video->getApiCode())->getPublicVideoData($this->_getParsedVideoId($data->getVideoLink()));
                        $video->setReadOnly(1);
                        $video->setState(AW_Vidtest_Model_Video::VIDEO_STATE_READY);
                    }                    
                    
                } elseif($data->getVideoType() == 'file') {
                    $entry = $this->_getApiModel()->uploadVideo($file, $data);
                }
                
                if ($entry && $entry->getError()){
                    throw new Exception($entry->getMessage());                    
                }
                if (!$entry){
                    throw new Exception(Mage::helper('vidtest')->__('Answer of service not responsed. Try upload your video again.'));
                }
                
                if (!$entry->getVideoUrl()) {
                    throw new Exception(Mage::helper('vidtest')->__("You can't add this video. It's not for share"));
                }

                $video->setApiVideoId($entry->getId());
                if (!$entry->getProcessing()){
                    $video->setApiVideoUrl($entry->getVideoUrl());
                    $video->setThumbnail($entry->getThumbnailUrl());
                    $video->setTime($entry->getTime());
                }

                $date = new Zend_Date();
                $video->setCreatedAt($date->toString('YYYY-MM-dd HH:mm'));

                $video->save();

                if (Mage::getStoreConfig(self::GET_STATUS_PATH)){
                    if ($data->getVideoType() == 'link'){
                        Mage::helper('vidtest')->addCustomerSuccess('Your video has been successfully added');
                    } elseif($data->getVideoType() == 'file') {
                        Mage::helper('vidtest')->addCustomerSuccess('Your video has been accepted for processing');

                        $video->setStatus(AW_Vidtest_Model_Video::VIDEO_STATUS_PROCESSING);
                        $video->save();
                    }
                } else {
                    Mage::helper('vidtest')->addCustomerSuccess('Your video has been accepted for moderation');
                }

            } catch (Exception $e) {
                Mage::helper('vidtest')->addCustomerError($e->getMessage());
            }

            $this->_redirectReferer();

            
        } else {
            $this->_redirectReferer();
        }
    }
}